package com.example.demo.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.Result;
import com.example.demo.common.Config;
import com.example.demo.common.Constent;
import com.example.demo.dao.LoginUserMapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.entity.LoginUser;
import com.example.demo.entity.User;
import com.example.demo.exception.CodeEnums;
import com.example.demo.exception.SPIPException;
import com.example.demo.intf.LoginInterface;
import com.example.demo.util.ConverterUtil;
import com.example.demo.util.HttpClientUtil;
import com.example.demo.util.HttpClientUtil.Method;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.MD5Util;
import com.example.demo.util.SequenceUtil;
import com.google.common.base.Objects;

import io.shardingsphere.api.HintManager;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author 88377761
 *
 */
@RestController
public class LoginImpl implements LoginInterface {
	/**
	 * @param name
	 * @return create by zy 88377761
	 */

	@Autowired
	UserMapper userMapping;

	@Autowired
	LoginUserMapper loginUserMapper;

	@Override
	public Result login(User user) throws SPIPException {
		Result result = new Result();
		if (StringUtils.isBlank(user.getUserName()))
			throw new SPIPException(CodeEnums.USER_EEEOR_10001);
		String password = user.getPassword();
		user.setPassword(MD5Util.getMD5(password));
		User userRes = userMapping.selectOne(user);
		if (userRes == null)
			throw new SPIPException(CodeEnums.USER_EEEOR_10002);
		// 生成JWT
		String token = JwtUtil.buildJWT(userRes.getUserName(), ConverterUtil.toString(userRes.getId()),
				60 * 60 * 24 * 10);
		// new一个Cookie对象,键值对为参数
		// Cookie cookie = new Cookie("token", token);
		// // tomcat下多应用共享
		// cookie.setPath("/");
		// cookie.setMaxAge(60 * 60);
		// response.addCookie(cookie);
		result.setData(userRes);
		result.setToken(token);
		return result;
	}

	@Override
	public Result loginForApp(LoginUser user) throws SPIPException {
		Result result = new Result();
		if (StringUtils.isBlank(user.getUserMobile()))
			throw new SPIPException(CodeEnums.USER_EEEOR_10003);
		String password = user.getUserPass();
		user.setUserPass(MD5Util.getMD5(password));
		LoginUser userRes = loginUserMapper.selectOne(user);
		if (userRes == null)
			throw new SPIPException(CodeEnums.USER_EEEOR_10002);
		userRes.setUserHeadPortrait(Constent.getImgUrl("user", userRes.getUserId().toString()));
		// 生成JWT
		String token = JwtUtil.buildJWT(userRes.getUserNikename(), ConverterUtil.toString(userRes.getUserId()),
				60 * 60 * 24 * 90);
		result.setData(userRes);
		result.setToken(token);
		return result;
	}

	@Override
	public Result register(LoginUser user) throws SPIPException {
		if (StringUtils.isBlank(user.getUserNikename()))
			throw new SPIPException(CodeEnums.USER_EEEOR_10001);
		if (StringUtils.isBlank(user.getUserMobile()))
			throw new SPIPException(CodeEnums.USER_EEEOR_10003);
		LoginUser param = new LoginUser();
		param.setUserMobile(user.getUserMobile());
		HintManager hintManager = HintManager.getInstance();
		LoginUser res = loginUserMapper.selectOne(param);
		hintManager.close();
		if (res != null)
			throw new SPIPException(CodeEnums.USER_EEEOR_10004);
		String password = user.getUserPass();
		user.setUserPass(MD5Util.getMD5(password));
		user.setUserId(SequenceUtil.getId("app_login_user"));
		user.setCreator(user.getUserId());
		user.setCreateDttm(new Date());
		user.setUpdater(user.getUserId());
		user.setUpdateDttm(new Date());
		loginUserMapper.insertSelective(user);
		return Result.getOk();
	}

	@Override
	public Result checking(LoginUser user) throws SPIPException {
		String url = "http://v.juhe.cn/sms/send";// 请求接口地址
		Map<String, String> params = new HashMap<>();// 请求参数
		params.put("mobile", user.getUserMobile());// 接收短信的手机号码
		params.put("tpl_id", Config.getTemplateId());// 短信模板ID，请参考个人中心短信模板设置
		params.put("tpl_value", "#code#=" + user.getCode());// 变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a
															// href="http://www.juhe.cn/news/index/id/50"
															// target="_blank">详细说明></a>
		params.put("key", Config.getAppKey());// 应用APPKEY(应用详细页查询)
		params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
		String res = HttpClientUtil.requestUrl(url, params, Method.POST, null, null);
		if (StringUtils.isBlank(res))
			throw new SPIPException(CodeEnums.USER_EEEOR_10006);
		JSONObject jsonObject = JSON.parseObject(res);
		if (!Objects.equal(0, jsonObject.getInteger("error_code")))
			throw new SPIPException(jsonObject.getString("reason"));
		return Result.getOk();
	}

	@Override
	public Result retrieve(LoginUser user) throws SPIPException {
		if (StringUtils.isBlank(user.getUserMobile()))
			throw new SPIPException(CodeEnums.USER_EEEOR_10003);
		LoginUser param = new LoginUser();
		param.setUserMobile(user.getUserMobile());
		LoginUser res = loginUserMapper.selectOne(param);
		if (res == null)
			throw new SPIPException(CodeEnums.USER_EEEOR_10005);
		String password = user.getUserPass();
		user.setUserPass(MD5Util.getMD5(password));
		user.setUpdater(user.getUserId());
		user.setUpdateDttm(new Date());

		Example example = new Example(LoginUser.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userMobile", user.getUserMobile());
		loginUserMapper.updateByExampleSelective(user, example);
		return Result.getOk();
	}

}
